package com.bwie.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.remote.AuthRemote;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Admin;
import com.bwie.common.domain.request.AdminRequest;
import com.bwie.common.domain.response.TokenResponse;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.common.utils.TelSmsUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthRemote remote;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * 根据手机号获取验证码
     * @param adminPhone
     */
    @Override
    public void getCode(String adminPhone) {
        if (StringUtils.isBlank(adminPhone)){
            throw new RuntimeException("手机号不能为空");
        }

        String randomNumbers = RandomUtil.randomNumbers(4);

        redisTemplate.opsForValue().set(adminPhone,randomNumbers);

        TelSmsUtils.sendSms(adminPhone,new HashMap<String,String>(){{
            put("code",randomNumbers);
        }});
    }

    /**
     * 登录
     * @param request
     * @return
     */
    @Override
    public TokenResponse login(AdminRequest request) {
        if (StringUtils.isAnyBlank(request.getAdminPhone(),request.getCode())){
            throw new RuntimeException("手机号或验证码不能为空");
        }

        Admin admin = remote.findByAdminPhone(request.getAdminPhone()).getData();
        if (admin == null){
            throw new RuntimeException("请注册");
        }

        if (!redisTemplate.hasKey(request.getAdminPhone())){
            throw new RuntimeException("验证码已过期");
        }

        String randomCode = redisTemplate.opsForValue().get(request.getAdminPhone());
        if (!randomCode.equals(request.getCode())){
            throw new RuntimeException("验证码错误");
        }

        HashMap<String, Object> map = new HashMap<>();
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSONObject.toJSONString(admin),20,TimeUnit.MINUTES);
        TokenResponse response = new TokenResponse();
        response.setToken(token);
        response.setExpireTime("20MINUTES");
        return response;
    }

    /**
     * 获取用户信息
     * @return
     */
    @Override
    public Admin info() {
        String token = httpServletRequest.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String admin = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        Admin admin1 = JSONObject.parseObject(admin, Admin.class);
        return admin1;
    }


    /**
     * 退出
     */
    @Override
    public void logout() {
        String token = httpServletRequest.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        redisTemplate.delete(TokenConstants.LOGIN_TOKEN_KEY + userKey);
    }
}
